package com.example.autopia.view.Activities

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.autopia.databinding.ActivityLikeNewsBinding
import com.example.autopia.model.Item.News
import com.example.autopia.model.Repositories.NewsRepository
import com.example.autopia.model.Repositories.UsersRepository
import com.example.autopia.view.Adapters.NewsAdapter
import com.example.autopia.view.Listeners.ActionNewsListener
import com.example.autopia.view.Listeners.PostNewsListener
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase

class LikeNewsActivity : AppCompatActivity() {
    private lateinit var binding: ActivityLikeNewsBinding
    private val newsRepository = NewsRepository()
    private val userRepository = UsersRepository()
    private val adapter = NewsAdapter()
    private val firebaseAuth = Firebase.auth

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityLikeNewsBinding.inflate(layoutInflater)
        setContentView(binding.root)

        binding.btBack.setOnClickListener {//Назад
            finish()
        }

        binding.recyclerView.adapter = adapter
        getData()//Первичное выставление данных

        adapter.attachListenerPost(object : PostNewsListener {
            override fun onAddCommentClick(news: News) {//Добавление коментария
                val intent = Intent(this@LikeNewsActivity, CommentsActivity::class.java)
                intent.putExtra("newsId", news.id)
                startActivity(intent)
            }

            override fun onAddLikeClick(news: News, isAdd: Boolean) {//Добавление/убавление лайка
                if (isAdd) {
                    newsRepository.addLike(newsId = news.id)
                    userRepository.addLikesNews(firebaseAuth.currentUser?.uid ?: "", news.id)
                } else {
                    newsRepository.removeLike(newsId = news.id)
                    userRepository.removeLikesNews(firebaseAuth.currentUser?.uid ?: "", news.id)
                }
            }

            override fun onMoreClick(news: News) {//Поделиться новостью
                val intent = Intent(Intent.ACTION_SEND)
                intent.type = "text/plain"
                intent.putExtra(
                    Intent.EXTRA_TEXT,
                    "Обсуждение из 'Autopia'" + "\n \n" + news.title + "\n \n" + news.mainText + "\n \n" + news.name
                )
                startActivity(Intent.createChooser(intent, "Поделиться с помощью"))
            }

            override fun onDeleteClick(news: News) {//Удаление записи
                newsRepository.deleteNews(newsId = news.id)
                Toast.makeText(this@LikeNewsActivity, "Обсуждение удалено", Toast.LENGTH_SHORT)
                    .show()
                getData()
            }

            override fun onChannelCLick(userid: String) {//Переход на обсуждения пользователя
                val intent = Intent(this@LikeNewsActivity, MyNewsActivity::class.java)
                intent.putExtra("id", userid)
                startActivity(intent)
            }
        })

        adapter.attachListenerAction(object : ActionNewsListener {
            //Не используется
            override fun onAddNewsClick() {}
            override fun onMyNewsClick() {}
            override fun onNewsChannelsClick() {}
        })
    }

    private fun getData() {
        var list = ArrayList<News>()
        val items = newsRepository.getAllItems()
        items.observe(this) {//Пока не получим данные с новостями
            val sortList = it.sortedByDescending { news -> news.time }
            list.addAll(sortList)
            val user = userRepository.getUserById(firebaseAuth.currentUser?.uid ?: "")
            user.observe(this) { curUser ->//Пока не получим данные о пользователе
                if (curUser.likesNewsList != null) {//Есть ли понравившиеся , или нету
                    list =
                        list.filter { news -> curUser.likesNewsList.contains(news.id) } as ArrayList<News>
                    if (list.size == 0) {
                        binding.error.visibility = View.VISIBLE
                        binding.recyclerView.visibility = View.INVISIBLE
                    }
                    list.add(list.size, News("1", "", "1", 1, null, "1", "1", 4, ""))

                } else {
                    binding.error.visibility = View.VISIBLE
                    binding.recyclerView.visibility = View.INVISIBLE
                }

                adapter.setData(list, curUser.likesNewsList!!)
                binding.loading.visibility = View.GONE
            }
        }
    }
}